<template>
  <div v-loading="!form">
    <el-form
      v-if="form"
      ref="goodsForm"
      :model="form"
      :rules="rules"
      label-width="20%"
      label-suffix="："
      class="form-fixed"
      @submit.native.prevent
    >
      <form-group title="基础信息">
        <el-form-item
          label="标题"
          prop="name"
          inline-message
          class="form-item--medium"
        >
          <el-input
            ref="formInput.name"
            v-model="form.name"
            maxlength="50"
            show-word-limit
          />
          <div class="form-item__tips">
            标题中请勿使用制表符、换行符。若填入制表符、换行符，系统将自动替换成空格。
            建议将以下推荐词添加至标题中以提升您的商品表达，请只添加符合您商品描述的内容：动漫学生毛绒卡通儿童
          </div>
        </el-form-item>
        <el-form-item
          label="描述信息"
          prop="description"
          class="form-item--medium"
        >
          <el-input
            v-model="form.description"
            type="textarea"
            maxlength="200"
            show-word-limit
          />
          <div class="form-item__tips">商品描述尽量简洁扼要的表示说明售卖商品的内容</div>
        </el-form-item>
        <el-form-item
          label="关键词"
          prop="tags"
          class="form-item--medium"
        >
          <el-input v-model="form.tags" />
          <div class="form-item__tips">多个关键词请使用空格或者英文状态下的逗号分割</div>
        </el-form-item>
        <el-form-item
          v-if="canUpdateCategory"
          label="商品分类"
          prop="category_id"
        >
          <el-cascader
            ref="formInput.category_id"
            v-model="form.category_id"
            :props="cascaderProps"
            :options="categorys"
          />
        </el-form-item>
        <el-form-item
          label="品牌"
          prop="brand_id"
        >
          <el-select
            v-model="form.brand_id"
            filterable
            clearable
            placeholder="可输入品牌名称检索"
          >
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="select-brand">
                <span>{{ item.name }}</span>
                <el-image
                  v-if="item.brand"
                  :src="item.brand"
                  fit="contain"
                />
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </form-group>
      <form-group title="价格库存">
        <el-form-item label="启用多规格">
          <el-switch v-model="enableMultiSpecs" />
        </el-form-item>
        <div v-if="enableMultiSpecs">
          <sku-spec-form
            ref="skusForm"
            v-model="form"
            validate-ref="skusForm2"
            :skus="skus"
            :specs="specs"
          />
        </div>
        <template v-else>
          <sku-items
            ref="formInput.skus[0]"
            v-model="form.skus[0]"
            prop-name="skus[0]"
          />
        </template>
      </form-group>
      <form-group title="售卖设置">
        <el-form-item label="是否限制积分使用">
          <el-switch
            v-model="form.limitMaxCredit"
            :active-value="1"
            :inactive-value="0"
          />
          <div class="form-item__tips">开启后将按照设置的“最大使用积分数量”进行计算</div>
        </el-form-item>
        <number-input
          v-if="form.limitMaxCredit"
          v-model="form.max_credit"
          label="最大使用积分数量"
          prop="max_credit"
          :step="1"
          :min="0"
          step-strictly
          append="分"
        >
          <div
            slot="hint"
            class="form-item__tips"
          >
            限制使用积分特别提醒：
            <span
              v-if="form.max_credit>0"
              class="line-small tips-warning"
            >用户购买商品最多可用 {{ form.max_credit }} 积分 抵扣 {{ form.max_credit/10 }} 元</span>
            <span
              v-else
              class="line-small tips-warning"
            >当前商品不能使用积分抵扣</span>
          </div>
        </number-input>
        <el-form-item
          label="预约上架时间"
          prop="up_date"
        >
          <el-date-picker
            v-model="form.up_date"
            type="datetime"
            placeholder="预约上架时间"
          />
          <div class="form-item__tips">默认留空根据上架状态变更时间上架</div>
        </el-form-item>
        <el-form-item
          label="预约下架时间"
          prop="down_date"
        >
          <el-date-picker
            v-model="form.down_date"
            type="datetime"
            placeholder="预约下架时间"
          />
          <div class="form-item__tips">默认留空表示售完为止</div>
        </el-form-item>
        <el-form-item
          label="商品服务"
          prop="services"
        >
          <el-checkbox-group v-model="form.services">
            <el-checkbox
              v-for="item in services"
              :key="item.id"
              :label="item.id"
            >
              {{ item.title }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </form-group>
      <form-group title="物流信息">
        <el-form-item label="是否免邮">
          <el-switch
            v-model="form.freightFree"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item
          v-if="!form.freightFree"
          label="运费模板"
          prop="template_id"
        >
          <el-select
            ref="formInput.template_id"
            v-model="form.template_id"
            clearable
            value-key="id"
            placeholder="请选择运费模板"
          >
            <el-option
              v-for="item in freights"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <create-freight-template
            type="text"
            text="添加运费模板"
            class="ml-4"
            @select="onLoadFreight"
          />
        </el-form-item>
      </form-group>
      <form-group title="图文信息">
        <el-form-item
          ref="formInput.thumb"
          label="商品封面图"
          prop="thumb"
        >
          <uploader
            v-model="form.thumb"
            :ratio="1"
            width="120px"
            type="image"
            :max-allow-file-size="600*1024"
            tips="封面图片尺寸：800*800 像素；图片格式：jpg、png、jpeg，大小不能超过600kb。"
          />
        </el-form-item>
        <el-form-item
          ref="formInput.pictures"
          label="商品主图"
          prop="pictures"
        >
          <uploader
            v-model="form.pictures"
            :ratio="1"
            :limit="10"
            column-width="130px"
            multiple
            type="gallery"
            :max-allow-file-size="600*1024"
            tips="主图图片尺寸：800*800 像素；图片格式：jpg、png、jpeg，大小不能超过600kb。"
          />
        </el-form-item>
        <el-form-item
          label="商品视频"
          prop="video"
        >
          <uploader
            v-model="form.video"
            type="video"
            :drag="true"
            :ratio="16/9"
            :width="360"
          >
            <template #tips>
              <div>注意事项：</div>
              <ol class="tips-ol">
                <li>检查upload文件夹是否有读写权限。 </li>
                <li>PHP默认上传限制为2MB，需要在php.ini配置文件中修改“post_max_size”和“upload_max_filesize”的大小。</li>
                <li>视频支持手动输入外链视频地址或者上传本地视频文件</li>
                <li>必须上传.mp4视频格式</li>
                <li>视频文件大小不能超过500MB</li>
              </ol>
            </template>
          </uploader>
        </el-form-item>
        <el-form-item
          ref="formInput.body"
          label="商品详情"
          prop="body"
        >
          <uploader
            v-model="form.body"
            :ratio="1"
            column-width="500px"
            multiple
            type="mobile"
            :max-allow-file-size="600*1024"
            tips="商品详情展示内容图片无尺寸限制，添加完成后可进行顺序排列；图片格式：jpg、png、jpeg，大小不能超过600kb。"
          />
        </el-form-item>
      </form-group>
      <fixed-box>
        <el-form-item>
          <div>
            <el-button
              type="primary"
              @click="onSubmit"
            >提交保存</el-button>
          </div>
          <div>
            <slot name="steps" />
            <el-button @click="goBack">返回</el-button>
          </div>
        </el-form-item>
      </fixed-box>
    </el-form>
  </div>
</template>

<script>
import FormGroup from '@/components/Form/FormGroup'
import SkuSpecForm from './SkuSpecForm'
import SkuItems from './SkuItems'
import NumberInput from '@/components/Form/NumberInput'
import Uploader from '@/components/Uploader/index'
import CreateFreightTemplate from '@/components/FreightTemplate/create'
import FixedBox from '@/layout/components/FixedBox'
import { toTree } from '@/utils'
export default {
  name: 'GoodsBaseForm',
  components: {
    FormGroup,
    SkuSpecForm,
    SkuItems,
    NumberInput,
    Uploader,
    CreateFreightTemplate,
    FixedBox
  },
  inject: ['goBack'],
  props: {
    value: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      enableMultiSpecs: false,
      cascaderProps: { value: 'id', label: 'name', emitPath: true },
      rules: {
        name: [{ required: true, message: '请输入商品名称！', trigger: 'blur' }],
        category_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        thumb: [{ required: true, message: '请上传商品封面图片', trigger: 'change' }],
        pictures: [
          {
            type: 'array',
            required: true,
            message: '请至少上传一张轮播展示图片',
            trigger: 'change'
          }
        ],
        template_id: [{ required: true, message: '请选择运费模板', trigger: 'change' }],
        body: [
          {
            type: 'array',
            required: true,
            message: '请设置商品详情信息'
          }
        ],
        region: [{ required: true, message: '请选择活动区域', trigger: 'change' }],
        date1: [
          {
            type: 'date',
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }
        ],
        date2: [
          {
            type: 'date',
            required: true,
            message: '请选择时间',
            trigger: 'change'
          }
        ],
        type: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'change'
          }
        ],
        resource: [{ required: true, message: '请选择活动资源', trigger: 'change' }],
        desc: [{ required: true, message: '请填写活动形式', trigger: 'blur' }],
        sku: {
          price: [{ required: true, message: '请设置商品价格', trigger: 'blur' }],
          stock: [{ required: true, message: '请设置商品价格', trigger: 'blur' }]
        }
      },
      form: null,
      brands: [],
      freights: [],
      categorys: [],
      services: [],
      skus: [],
      specs: [],
      safeAttributes: []
    }
  },
  computed: {
    canUpdateCategory() {
      return this.safeAttributes.indexOf('category_id') !== -1
    }
  },
  mounted() {
    this.onLoad()
  },
  methods: {
    onLoad() {
      this.$http.commodity.formConfig(this.value).then(res => {
        console.log('onLoadConfig', res.data)
        this.onMountData(res.data)
      })
    },
    onMountData(data) {
      const { form, categorys, brands, services, freights, skus, specs, safeAttributes } = data
      this.form = { ...form }
      if (categorys && categorys.length > 0) {
        this.categorys = toTree(categorys)
      }
      this.enableMultiSpecs = skus.length > 1
      this.brands = brands
      this.services = services
      this.freights = freights
      this.skus = skus
      this.specs = specs
      this.safeAttributes = safeAttributes
    },
    onSubmit() {
      this.$refs.goodsForm.validate((valid, obj) => {
        if (valid) {
          var skusForm = this.$refs['skusForm']
          if (this.enableMultiSpecs && skusForm) {
            if (skusForm.toggleFormValidate()) {
              this.submit()
            }
          } else {
            this.form.skus = this.form.skus.slice(0, 1)
            this.submit()
          }
        } else {
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `formInput.${i}`
            break
          }
          var dom = this.$refs[firstErrorElname]
          console.log(dom, this.$refs)
          if (dom) {
            dom.$refs.input && dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          console.log('error submit!!', this.form)
          return false
        }
      })
    },
    submit() {
      this.$http.commodity.update(this.form, this.value).then(res => {
        if (res.data) {
          this.$emit('saved', res.data)
        }
      })
    },
    onLoadFreight(data) {
      if (data) {
        this.freights.push(data)
        this.form.template_id = data.id
      }
    }
  }
}
</script>
